package excutor;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author zhu_shuai
 * @since 2021/6/20
 */
public class ThreadPoolExecutorDemo {
    private static AtomicInteger atomicInteger = new AtomicInteger(0);

    public static void main(String[] args) {

        BlockingQueue blockingQueue = new LinkedBlockingDeque(10);
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(4, 8, 30, TimeUnit.SECONDS,
                blockingQueue, Executors.defaultThreadFactory(),
                // new ThreadPoolExecutor.AbortPolicy() // 抛出异常
                // new ThreadPoolExecutor.CallerRunsPolicy() // 让调用线程去执行
                // new ThreadPoolExecutor.DiscardPolicy()  // 直接丢弃
                new ThreadPoolExecutor.DiscardOldestPolicy()  // 丢弃队列里最近的一个任务，并执行当前任务
        );

        for (int i = 0; i < 100; i++) {
            int finalI = i;
            Thread thread = new Thread(() -> {
                System.out.println(Thread.currentThread().getName() + " ---start------" + finalI);
                atomicInteger.addAndGet(1);
                try {
                    Thread.sleep(1000);
                    System.out.println(Thread.currentThread().getName() + " ---- end------" + finalI);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
            try {
                threadPoolExecutor.execute(thread);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        threadPoolExecutor.shutdown();
        while (true) {
            if (threadPoolExecutor.isTerminated()) {
                System.out.printf("共%d执行%n", atomicInteger.get());
                break;
            }
        }

        ExecutorService executorService = Executors.newCachedThreadPool();
        ExecutorService executorService1 = Executors.newFixedThreadPool(10);
        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(10);
        ExecutorService executorService2 = Executors.newSingleThreadExecutor();
    }
}
